<template>
  <div class="p-6">
    <div class="flex justify-between items-center mb-6">
      <h1 class="text-2xl font-bold">码牌管理</h1>
      <a-button type="primary" @click="showCreateModal = true">
        <template #icon><plus-outlined /></template>
        新建码牌
      </a-button>
    </div>

    <!-- 搜索栏 -->
    <a-card class="mb-6">
      <a-form layout="inline" :model="searchForm">
        <a-form-item label="码牌名称">
          <a-input v-model:value="searchForm.name" placeholder="请输入码牌名称" />
        </a-form-item>
        <a-form-item label="状态">
          <a-select v-model:value="searchForm.status" style="width: 120px">
            <a-select-option value="">全部</a-select-option>
            <a-select-option value="active">活跃</a-select-option>
            <a-select-option value="inactive">未激活</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="handleSearch">
            <template #icon><search-outlined /></template>
            搜索
          </a-button>
          <a-button class="ml-2" @click="handleReset">
            <template #icon><reload-outlined /></template>
            重置
          </a-button>
        </a-form-item>
      </a-form>
    </a-card>

    <!-- 码牌列表 -->
    <a-card>
      <a-table
        :columns="columns"
        :data-source="tableData"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
      >
        <!-- 状态列 -->
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <a-tag :color="record.status === 'active' ? 'success' : 'default'">
              {{ record.status === 'active' ? '活跃' : '未激活' }}
            </a-tag>
          </template>
          <!-- 操作列 -->
          <template v-if="column.key === 'action'">
            <a-space>
              <a @click="handleView(record)">查看</a>
              <a-divider type="vertical" />
              <a @click="handleEdit(record)">编辑</a>
              <a-divider type="vertical" />
              <a-popconfirm
                title="确定要删除这个码牌吗？"
                @confirm="handleDelete(record)"
              >
                <a class="text-red-500">删除</a>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 查看二维码弹窗 -->
    <a-modal
      v-model:open="showQrcodeModal"
      title="二维码预览"
      :footer="null"
      width="400px"
    >
      <div class="text-center">
        <div class="mb-4">
          <qrcode-vue :value="currentQrcode.url" :size="200" level="H" />
        </div>
        <h3 class="text-lg font-bold mb-2">{{ currentQrcode.name }}</h3>
        <p class="text-gray-500 mb-4">ID: {{ currentQrcode.id }}</p>
        <a-descriptions :column="1" size="small">
          <a-descriptions-item label="创建时间">
            {{ currentQrcode.createTime }}
          </a-descriptions-item>
          <a-descriptions-item label="状态">
            <a-tag :color="currentQrcode.status === 'active' ? 'success' : 'default'">
              {{ currentQrcode.status === 'active' ? '活跃' : '未激活' }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="备注">
            {{ currentQrcode.remark || '无' }}
          </a-descriptions-item>
        </a-descriptions>
      </div>
    </a-modal>

    <!-- 新建码牌弹窗 -->
    <a-modal
      v-model:open="showCreateModal"
      title="创建码牌"
      @ok="handleCreate"
      :confirmLoading="createLoading"
    >
      <a-form
        :model="createForm"
        layout="vertical"
      >
        <a-form-item
          label="码牌名称"
          name="name"
          :rules="[{ required: true, message: '请输入码牌名称' }]"
        >
          <a-input v-model:value="createForm.name" placeholder="请输入码牌名称" />
        </a-form-item>
        <a-form-item
          label="备注"
          name="remark"
        >
          <a-textarea v-model:value="createForm.remark" placeholder="请输入备注信息" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { message } from 'ant-design-vue'
import QrcodeVue from 'qrcode.vue'
import { mockData, type QrcodeItem } from './data'
import {
  PlusOutlined,
  SearchOutlined,
  ReloadOutlined,
} from '@ant-design/icons-vue'

// 搜索表单
const searchForm = reactive({
  name: '',
  status: '',
})

// 表格列定义
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
  },
  {
    title: '码牌名称',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
  },
]

// 表格数据
const loading = ref(false)
const tableData = ref<QrcodeItem[]>(mockData)
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: mockData.length,
})

// 二维码详情
const showQrcodeModal = ref(false)
const currentQrcode = reactive<QrcodeItem>({
  id: '',
  name: '',
  status: 'inactive',
  createTime: '',
  url: '',
  remark: '',
})

// 新建码牌
const showCreateModal = ref(false)
const createLoading = ref(false)
const createForm = reactive({
  name: '',
  remark: '',
})

// 处理搜索
const handleSearch = () => {
  loading.value = true
  // 模拟搜索
  setTimeout(() => {
    const filtered = mockData.filter(item => {
      const nameMatch = !searchForm.name || item.name.includes(searchForm.name)
      const statusMatch = !searchForm.status || item.status === searchForm.status
      return nameMatch && statusMatch
    })
    tableData.value = filtered
    pagination.total = filtered.length
    loading.value = false
  }, 500)
}

// 处理重置
const handleReset = () => {
  searchForm.name = ''
  searchForm.status = ''
  handleSearch()
}

// 处理表格变化
const handleTableChange = (pag: any) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
}

// 查看码牌
const handleView = (record: QrcodeItem) => {
  Object.assign(currentQrcode, record)
  showQrcodeModal.value = true
}

// 编辑码牌
const handleEdit = (record: QrcodeItem) => {
  message.info('编辑功能开发中')
}

// 删除码牌
const handleDelete = (record: QrcodeItem) => {
  const index = tableData.value.findIndex(item => item.id === record.id)
  if (index > -1) {
    tableData.value.splice(index, 1)
    message.success('删除成功')
  }
}

// 新建码牌
const handleCreate = () => {
  const baseDate = '20250601'
  const randomNum = String(Math.floor(Math.random() * 90000) + 10000)
  const id = `QR${baseDate}${randomNum}`
  const newQrcode: QrcodeItem = {
    id,
    name: createForm.name,
    status: 'inactive',
    createTime: new Date().toLocaleString(),
    url: `https://example.com/pay/${id}`,
    remark: createForm.remark,
  }
  tableData.value.unshift(newQrcode)
  message.success('创建成功')
  showCreateModal.value = false
  createForm.name = ''
  createForm.remark = ''
}
</script>

<style scoped>
.ant-card {
  border-radius: 8px;
}

.ant-table-wrapper {
  border-radius: 8px;
  overflow: hidden;
}

.ant-tag {
  border-radius: 4px;
}
</style>